<?php
/**
 * Created by PhpStorm.
 * User: DaibiDaddy
 * Date: 2016/5/26
 * Time: 14:40
 */

namespace AdminsBundle\Controller;

use AdminsBundle\Entity\Product as Entity;
use AdminsBundle\Entity\ProductMeta;
use AdminsBundle\Entity\ProductNote;
use AdminsBundle\Entity\ProductProduce;
use AdminsBundle\Entity\ProductShow;
use AdminsBundle\Entity\ProductStatistic;
use AdminsBundle\Helper\MyForms;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Component\HttpFoundation\Request;
use AdminsBundle\Helper\MyController;

class ProductController extends MyController{

    /*快速复制项目通用化配置*/
    private $entity;
    private $entityName = "Product";
    private $listKeys = array("id","name","no","num","price");
    private $searchKeys = array("name","price","searchInfo");
    private $conditionKeys = array("cid","isHot","isNew","isSale","isFamous","isWebIndex");
    private $editKeys = array("Num","isWebIndex","isNew","isHot","isSale","isFamous");
    private $perPage = 10;

    /**
     * @route("Product/add",name="ProductPreAdd")
     */
    public function add()
    {
        $this->entity = new Entity();
        $form = $this->createMyForm($this->entityName , $this->entity,   $this->generateUrl($this->entityName."DoAdd"));
        $show = $form->createView();
        $data = array(
            "title" => "新增产品",
            "submitUrl" => $this->generateUrl($this->entityName."DoAdd"),
            "submitType" => "Post",
            "show"   => $show,
        );
        return $this->render("AdminsBundle:".$this->entityName.":add.php.twig",$data);
    }

    /**
     * @route("Product/add/do",name="ProductDoAdd")
     *
     * @Method({"GET", "POST"})
     */
    public function doAdd(Request $request)
    {
        if (!$attrs = $this->getParamRequired("attrs",$request)) {return $this->js_out($this->generateUrl("ProductPreAdd"),"请设置参数");}

        $Category = $this->get("xiao_zhu.category_model");
        $searchInfo = $Category->makeUpCategory($attrs);
        $this->entity = new Entity();
        $form = $this->createMyForm($this->entityName ,  $this->entity);
        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $this->entity->setCid($searchInfo["cat"][0]);
            $searchInfo = json_encode($searchInfo);
            $this->entity->setSearchInfo($searchInfo);
            $em->persist($this->entity);
            $em->flush();
            //添加空白产品标签
            $produce = New ProductNote();
            $produce->setId($this->entity->getId());
            $produce->setIsFamous(0);
            $produce->setIsHot(0);
            $produce->setIsNew(0);
            $produce->setIsSale(0);
            $produce->setIsWebIndex(0);
            //todo 检查存在
            //todo 如果存在 删除之
            $em->persist($produce);
            $em->flush();
            //添加空白产品参数
            $produce = New ProductMeta();
            $produce->setId($this->entity->getId());
            $produce->setCreate(time());
            $produce->setUpdate(time());
            $produce->setNote("");
            //todo 检查存在
            //todo 如果存在 删除之
            $em->persist($produce);
            $em->flush();
            //添加空白产数据统计
            $produce = New ProductStatistic();
            $produce->setId($this->entity->getId());
            $produce->setCollect(0);
            $produce->setOpen(0);
            $produce->setSearch(0);
            $produce->setSell(0);
            //todo 检查存在
            //todo 如果存在 删除之
            $em->persist($produce);
            $em->flush();
            //添加空白生产厂家
            $produce = New ProductProduce();
            $produce->setId($this->entity->getId());
            $produce->setCompany("");
            $produce->setAddress("");
            $produce->setTime("");
            //todo 检查存在
            //todo 如果存在 删除之
            $em->persist($produce);
            $em->flush();
            //添加空白展示信息
            $show = New ProductShow();
            $show->setId($this->entity->getId());
            $show->setTitle("");
            $show->setInfo("");
            $show->setCover("");
            $show->setImg1("");
            $show->setImg2("");
            $show->setImg3("");
            $show->setIntro("");
            //todo 检查存在
            //todo 如果存在 删除之
            $em->persist($show);
            $em->flush();
            return $this->redirectToRoute($this->entityName.'Lists');
        } else {
            return $this->js_out($this->generateUrl($this->entityName."PreAdd"),"系统错误，请联系管理员");
        }
    }

    /**
     * @route("Product/edit/{id}",name="ProductPreEdit")
     */
    public function edit(Entity $entity)
    {
        $action = $this->generateUrl($this->entityName."DoEdit",array("id"=>$entity->getId()));
        $form = $this->createMyForm($this->entityName ,  $entity ,  $action );
        $show = $form->createView();

        $cat = json_decode($entity->getSearchInfo(),true);

        $data = array(
            "title" => "管理产品",
            "submitUrl" => $this->generateUrl($this->entityName."DoAdd"),
            "submitType" => "Post",
            "show"   => $show,
            "catData"   => $cat,
        );
        return $this->render("AdminsBundle:".$this->entityName.":add.php.twig",$data);
    }

    /**
     * @route("Product/edit/{id}/do",name="ProductDoEdit")
     *
     * @Method({"GET", "POST"})
     */
    public function doEdit(Request $request,Entity $entity)
    {
        if (!$attrs = $this->getParamRequired("attrs",$request)) {return $this->js_out($this->generateUrl("ProductPreAdd"),"请设置参数");}

        $Category = $this->get("xiao_zhu.category_model");
        $searchInfo = $Category->makeUpCategory($attrs);

        $form = $this->createMyForm($this->entityName ,  $entity );
        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $entity->setCid($searchInfo["cat"][0]);
            $searchInfo = json_encode($searchInfo);
            $entity->setSearchInfo($searchInfo);
            $em->persist($entity);
            $em->flush();
            return $this->redirectToRoute($this->entityName.'Lists');
        } else {
            return $this->js_out($this->generateUrl($this->entityName."PreEdit",array("id"=>$entity->getId())),"系统错误，请联系管理员");
        }
    }

    /**
     * @route("Product",name="ProductLists")
     */
    public function lists()
    {
        /*分页配置*/
        if ($page   = $this->getParamRequired("page")){} else { $page = 1;}
        $per_page   = $this->perPage;

        $lists = $this->getLists($page,$per_page);
        $total = $lists["total"];

        /*URL配置*/
        $urls = array(
            "toolUrl"=>$this->generateUrl($this->entityName."Tools"),
            "addUrl"=>$this->generateUrl($this->entityName."PreAdd"),
        );
        $rep = $this->getDoctrine()->getManager()->getRepository("AdminsBundle:Category");
        $classes = $rep->findAll();

        return $this->render("AdminsBundle:".$this->entityName.":list.php.twig", array(
            'title'     => "产品列表",
            "classes"   => $classes,
            'urls'      => $urls,
            'lists'     => $lists["data"],
            'page'      => $this->creatPage($this->generateUrl($this->entityName."Lists"),$total,$per_page),
        ));
    }

    /**
     * @route("Product/tools",name="ProductTools")
     */
    public function tools(Request $request)
    {

        if($__EVENTTARGET = $this->getParamRequired("__EVENTTARGET")){
            unset($_GET['__EVENTTARGET']);
        }else{
            return $this->js_out($this->entityName."Lists","参数丢失");
        }
        if($__EVENTARGUMENT = $this->getParamRequired("__EVENTARGUMENT")){
            unset($_GET['__EVENTARGUMENT']);
        }
        $em = $this->getDoctrine()->getManager();
        //如果是删除操作执行删除操作
        if ($__EVENTTARGET == "multiDelete") {
            if($ids = $this->getParamRequired("ids")){
                unset($_GET['ids']);
            }else{
                return $this->js_out($this->entityName."Lists","参数丢失");
            }
            if (is_array($ids) && !empty($ids)) {
                foreach ($ids as $id) {
                    $this->entity  = $em->find("AdminsBundle:".$this->entityName,$id);
                    $em->remove($this->entity);
                    //删除其他表信息
                }
                $em->flush();
            }
        }
        if ($__EVENTTARGET == "setAttr") {
            parse_str($__EVENTARGUMENT,$data);
            if (is_array($data) && isset($data["id"])) {
                $id = $data["id"];
                $this->entity  = $em->find("AdminsBundle:".$this->entityName,$id);
                unset($data["id"]);
                foreach ($data as $key => $val) {
                    if ( !in_array( $key , $this->editKeys ) ) { continue; }
                    switch ($key) {
                        case "Num":
                            $func = "set$key";
                            $this->entity->$func($val);
                            $em->persist($this->entity);
                            break;
                        default:
                            $ProductNote = $em->find("AdminsBundle:ProductNote",$id);
                            $func = "set$key";
                            $ProductNote->$func($val);
                            $em->persist($ProductNote);
                    }
                }

                $em->flush();
            }
        }
        //否则将参数传递至list
        $cond["cond"] = $request->get("cond");
        $queryStr = http_build_query($cond);
        if ($txtKeywords = $request->get("txtKeywords")) {
            $queryStr .= "&txtKeywords=".$txtKeywords;
        }
        return $this->redirect($this->generateUrl($this->entityName."Lists")."?".$queryStr);
    }
    private function getLists($page,$per_page)
    {
        $request = Request::createFromGlobals();
        $txtKeywords = $request->get("txtKeywords");
        $qb = $this
            ->getDoctrine()
            ->getManager()
            ->createQueryBuilder();

        $qb->from( "AdminsBundle:".$this->entityName , $this->entityName );
        if ($txtKeywords) {
            $search = $qb->expr()->orX();
            foreach ( $this->searchKeys as $key ) {
                $search->add( $this->entityName.".$key like :key" );
            }
            $qb->where( $search )->setParameter( "key" , "%$txtKeywords%" );}
        if ( $condition = $request->get("cond") ) {
            foreach ( $condition as $key => $val ) {
                if ( $val == "" || !in_array( $key , $this->conditionKeys ) ) { continue; }
                switch ($key) {
                    case "cid":
                        $qb->andWhere( $this->entityName.".$key = :val" )->setParameter( "val" , $val );
                        break;
                    default:
                        $qb->andWhere( "note.$key = :val" )->setParameter( "val" , $val );
                }

            }
        }
        $qb->orderBy( $this->entityName.".id" , "DESC" );
        //获取列表数目
        $qb->select( array( "COUNT(".$this->entityName.".id) as num" ) );
        $qb->leftJoin("AdminsBundle:ProductNote","note","WITH" , "note.id = ".$this->entityName.".id");
        $count = $qb->getQuery()->getSingleResult();
        //获取列表内容
        if ($count["num"] == 0) {
            $lists = array();
        }else{
            foreach ($this->listKeys as $key) {
                $select[] = $this->entityName.".".$key;
            }

            $select[] = "pp.company";
            $select[] = "pp.id as comId";
            $qb->leftJoin("AdminsBundle:ProductProduce","pp","WITH" , "pp.id = ".$this->entityName.".id");
            $select[] = "show.cover";
            $select[] = "show.id as showId";
            $qb->leftJoin("AdminsBundle:ProductShow","show","WITH" , "show.id = ".$this->entityName.".id");
            $select[] = "note.isWebIndex";
            $select[] = "note.isNew";
            $select[] = "note.isHot";
            $select[] = "note.isSale";
            $select[] = "note.isFamous";


            $qb->select($select);
            $qb->setFirstResult( $page * $per_page - $per_page );
            $qb->setMaxResults( $per_page );
            $lists = $qb->getQuery()->getResult();
        }
        return array(
            "total" => isset($count["num"]) ? $count["num"] : 0,
            "data"  => $lists
        );
    }

    /**
     * @route("Product/catSons",name="getCatSons")
     */
    public function getCatSons(Request $request)
    {
        if (!$id = $this->getParamRequired("id",$request)) {return die("ERROR");}
        $sons = $this->getDoctrine()->getManager()->getRepository("AdminsBundle:Category")->getCatSons($id);
        return $this->json_out(1,$id,$sons);
    }

    /**
     * @route("Product/catAttr",name="getCatAttr")
     */
    public function getCatAttr(Request $request)
    {
        if (!$id = $this->getParamRequired("id",$request)) {return die("ERROR");}
        $parent = $this->getDoctrine()->getManager()->getRepository("AdminsBundle:Category")->find($id);
        $rep = $this->getDoctrine()->getManager()->getRepository("AdminsBundle:CategoryAttribute");
        $sons = $rep->getAttr($id);
        $data = array();
        foreach ($sons as $key => $son) {
            $values = $this->getDoctrine()->getManager()->getRepository("AdminsBundle:CategoryAttributeValue")->getAttrVal($son["id"]);
            $data[] = array(
                "key" => $son,
                "val" => $values
            );
        }
        return $this->json_out(1,$parent->getParent(),$data);
    }
}